from flask import Blueprint,request,render_template,jsonify,redirect,url_for
from flask_login import login_user, LoginManager
from sqlalchemy.exc import SQLAlchemyError
from .forms import UserRegForm,UserLoginForm
from exts import db
from apps.members import  members_bp
from apps.users.models import  User
from apps.members.models import Member
# from apps.members.models import  Member
# 用户认证的回调函数
# @login_manager.user_loader
# def load_user(user_id):
#     return User.query.get(int(user_id))

@members_bp.route("/reg",methods=["GET","POST"])
def reg():
    if request.method=="GET":
        form_obj=UserRegForm()
        return render_template('shop/reg.html',form_obj=form_obj)
    if request.method=="POST":
        f=UserRegForm(request.form)
        if f.validate_on_submit():
            uname=f.username.data
            users=User.query.filter_by(username=uname).count()
            if users:
                info='用户已经存在'
            else:
                try:
                    user=User()
                    user.username=f.username.data
                    user.password=f.password.data
                    user.mobile=f.mobile.data
                    user.sex=1
                    user.email=f.email.data
                    user.birthday="2023-01-01"
                    user.level=1
                    user.status=1
                    db.session.add(user)
                    db.session.commit()
                    info='注册成功,请登陆'
                    return redirect(url_for('users.login'))
                except SQLAlchemyError as e:
                    print(e)
                    return render_template("shop/reg.html", form_obj=f, info=e)
            return render_template("shop/reg.html", form_obj=f,info=info)
        else:
            errors = f.errors
            return render_template("shop/reg.html", form_obj=f,info=errors)

@members_bp.route("/login",methods=["GET","POST"])
def login():
    if request.method == "GET":
        f = UserRegForm()
        return render_template('shop/login.html', form_obj=f)
    if request.method == "POST":
        f = UserLoginForm(request.form)
        if f.validate_on_submit():
            username = f.username.data
            pwd=f.password.data
            user = User.query.filter(User.username==username,User.password==pwd).first()
            if user:
                print(user)
                login_user(user)
                return redirect(url_for("basic.index"))
            return render_template('shop/login.html', form_obj=f,info="用户登录失败")
        else:
            errors = f.errors
            print(errors)
            return render_template("shop/login.html", form_obj=f, info=errors)

@members_bp.route("/index",methods=["GET","POST"])
def index():
    members = Member.query.all()
    # cates = func.binddata(0, 1)
    return render_template("shop/members/index.html", members=members)